package com.kuangstudy.service.list;

import com.kuangstudy.entity.Content;
import com.kuangstudy.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.MapFactoryBean;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: xuke
 * @time: 2021/6/11 23:37
 */
@Service
@Slf4j
public class PushContentService {

    @Autowired
    private RedisTemplate redisTemplate;

    public Content saveContent(Content content) {
        // 1: 保存内容到db中
        // 2: 把保存的内容写入到hash中
        Map<String, Object> stringObjectMap = null;
        try {
            stringObjectMap = ObjectUtils.objectToMap(content);
            String key = "weibo:content:" + content.getId();
            // 3: 把微博的内容保存到hash中
            HashOperations<String, String, Object> opsForHash = redisTemplate.opsForHash();
            opsForHash.putAll(key, stringObjectMap);
            // 4: 设置微博的有效期是30天过期
            this.redisTemplate.expire(key, 30, TimeUnit.DAYS);
            return content;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

}
